<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="4" labelWidth="100" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :selectionType="'single'"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onSyncTableData="tableChangeFun"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <AjaxButton size="small" type="primary" :click="exportClick">导出</AjaxButton>
      </template>
    </FilterTable>

    <!-- 选择经销商 -->
    <BaseDialog :visible.sync="dealerAction.visible" :title="dealerAction.title" destroyOnClose :containerStyle="{ height: 'calc(100% - 70px)', overflow: 'auto', paddingBottom: '70px' }">
      <searchDealerPanel :type="dealerAction.type" :row="dealerAction.data" @close="closeDealerDialog" @saveDialog="saveDealerDialog" />
    </BaseDialog>

    <Drawer :visible.sync="action.visible" :title="action.title" destroyOnClose width="70%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OrderPanel :type="action.type" :rowData="action.data" :chargePartition="chargePartition" :allUser="allUser" @closeDialog="closeHandler" />
    </Drawer>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import OrderPanel from './OrderPanel';
import { queryBalanceOem, getRepairTypes, getAllUser, getAllDealer, factoryExportsSettlement } from '@/api/repair/repairManage/repairFeeQuery/index.js';
import Cookies from 'js-cookie';
import searchDealerPanel from '@/pages/repair/mileageDateChange/mileageApprove/searchDealerPanel';
import { getPinpSelect, getChexSelect, getCheModelSelectTable, queryModelBySeriesId } from '@/api/repair/repairReception/customer/brand.js';
import { searchAllUserByRole } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { queryChargeDifferentiationList } from '@/api/repair/repairReception/repairBusinessManger';
import { getNameByIds } from '@/api/repair/common/index.js';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
export default {
  name: 'repairQuery',
  components: {
    OrderPanel,
    searchDealerPanel
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      fetchApi: queryBalanceOem,
      fetchParams: { xhrAbort: false },
      columns: this.createTableColumns(),
      dealerAction: { type: '', visible: false, title: '选择经销商', data: null },
      action: { type: 'add', visible: false, title: '维修工单明细', data: null },
      allUser: [],
      chargePartition: [],
      tableData: [],
      allDealer: [] // 所有的经销商信息
    };
  },
  created() {
    this.getRepairTypesFun();
    // this.getAllBrand();
    this.getAllUser();
    this.getAllDealer();
    this.getAllServiceAdvisor();
    this.queryChargeList(); // 查询收费区分，二级页面要用
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // 查询收费区分
    async queryChargeList() {
      const res = await queryChargeDifferentiationList();
      if (res.resultCode == 200) {
        let items = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE + '', text: x.CHARGE_PARTITION_NAME }));
        this.chargePartition = items;
        console.log(res.data, 'queryChargeList');
      }
    },
    async exportClick() {
      const [err, data] = await this.$refs.topFilter.GET_FORM_DATA();
      factoryExportsSettlement(data).then(res => {
        exportExcelFile(res.data, '维修费用查询表');
      });
    },
    // 获取销售顾问
    async getAllServiceAdvisor() {
      let params = { roleCode: 'DLR-FWGW' };
      const res = await searchAllUserByRole(params);
      let data = arrayObjDeWeight(res.data, 'USER_ID');
      if (res.resultCode == 200) {
        let serviceAdvisor = data.map(x => ({ text: x.EMPLOYEE_NAME, value: x.USER_ID + '' }));
        this.topFilterList.find(x => x.fieldName === 'serviceAdvisor').itemList = serviceAdvisor;
        this.columns.find(x => x.dataIndex === 'serviceAdvisor').filterItems = serviceAdvisor;
        this.columns.find(x => x.dataIndex === 'serviceAdvisor').dictItems = serviceAdvisor;
      }
    },
    // 获取所有的经销商
    async getAllDealer() {
      let res = await getAllDealer();
      if (res.resultCode == 200) {
        let allDealer = res.data.map(x => ({ text: x.dealerShortname, value: x.dealerCode + '' }));
        this.allDealer = allDealer;
        this.columns.find(x => x.dataIndex === 'ownerCode').dictItems = allDealer;
        // this.columns.find(x => x.dataIndex === 'ownerCode').filterItems = allDealer;
      }
    },
    // 获取所有的人员
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        this.allUser = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      }
    },
    // 获取所有的人员
    async getNameByIds(parmas) {
      let res = await getNameByIds(parmas);
      if (res.resultCode == 200) {
        let userList = res.data.map(x => ({ text: x.employeeName, value: x.employeeId + '' }));
        this.columns.find(x => x.dataIndex === 'serviceAdvisor').dictItems = userList;
        this.columns.find(x => x.dataIndex === 'chiefTechnician').dictItems = userList;
        // this.columns.find(x => x.dataIndex === 'lockUser').dictItems = userList;
        this.columns.find(x => x.dataIndex === 'testDriver').dictItems = userList;
      }
    },
    dealerTranslate() {
      let userIds = [];
      this.tableData.forEach(item => {
        userIds.push(item.serviceAdvisor);
        userIds.push(item.chiefTechnician);
        // userIds.push(item.lockUser);
        userIds.push(item.testDriver);
      });
      if (!userIds.length) return;
      let newUserIds = Array.from(new Set(userIds)); // 数组去重
      let userIdsStr = newUserIds.join(',');
      if (!userIdsStr.length) return;
      this.getNameByIds({ userIds: userIdsStr });
    },
    tableChangeFun(data) {
      this.tableData = data;
      this.dealerTranslate();
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerCode',
          hidden: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerShortName',
          placeholder: '请选择...',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.dealerAction = { type: '', visible: true, title: '选择经销商', data: {} };
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '是否被负结算',
          fieldName: 'isRed',
          placeholder: '请选择',
          itemList: [
            { value: 10041001, text: '是' },
            { value: 10041002, text: '否' }
          ]
        },

        {
          type: 'SELECT',
          label: '日期类型',
          fieldName: 'dateType',
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '开单日期' },
            { value: 2, text: '结算日期' },
            { value: 3, text: '结清日期' }
          ],
          change: val => {
            this.topFilterList.find(x => x.fieldName === 'startDate|endDate').disabled = !!!val;
            this.topFilterList.find(x => x.fieldName === 'startDate|endDate').initialValue = undefined;
          }
        },
        {
          type: 'RANGE_DATE',
          label: '时间',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          itemList: [],
          disabled: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.isEdit(props.row)} onClick={() => this.editHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },

        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.ownerCode}</span>;
          }
        },
        {
          title: '经销商名称',
          dataIndex: 'ownerShortName',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input',
          dictItems: [],
          render: props => {
            // 不能翻译就显示code
            let ownerShortName = props.row.ownerCode;
            if (this.allDealer.length) {
              let item = this.allDealer.find(x => x.value == props.row.ownerCode);
              if (item) {
                ownerShortName = item.text;
                props.row.ownerShortName = item.text; // 每一条数据增加一个字段，后台不存前端显示用
              }
            }
            return <span>{ownerShortName}</span>;
          }
        },

        {
          title: '工单号',
          dataIndex: 'roNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算单号',
          dataIndex: 'balanceNo',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '维修类型',
        //   dataIndex: 'repairTypeCode',
        //   width: 150,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '维修类型',
          dataIndex: 'repairTypeName',
          width: 150,
          sorter: true
        },

        {
          title: '服务顾问',
          dataIndex: 'serviceAdvisor',
          width: 150,
          sorter: true,
          dictItems: []
        },
        // {
        //   title: '锁定人',
        //   dataIndex: 'lockUser',
        //   width: 150,
        //   sorter: true,
        //   dictItems: []
        // },

        {
          title: '开单日期',
          dataIndex: 'roCreateDate',
          width: 150,
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          filterType: 'input'
        },

        {
          title: '指定技师',
          dataIndex: 'chiefTechnician',
          width: 150,
          sorter: true,
          dictItems: []
        },
        {
          title: '预交车时间',
          dataIndex: 'endTimeSupposed',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '试车员',
          dataIndex: 'testDriver',
          width: 150,
          sorter: true,
          dictItems: []
        },

        {
          title: '车主',
          dataIndex: 'ownerName',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人',
          dataIndex: 'deliverer',
          width: 150,
          sorter: true
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '送修人电话',
          dataIndex: 'delivererPhone',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人手机',
          dataIndex: 'delivererMobile',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算时间',
          dataIndex: 'balanceTime',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },

        {
          title: '结清时间',
          dataIndex: 'squareDate',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        }
      ];
    },

    // async getAllBrand() {
    //   let res = await getPinpSelect();
    //   if (res.resultCode == 200) {
    //     this.topFilterList.find(x => x.fieldName === 'brandId').itemList = res.data.map(x => ({ value: x.brandId + '', text: x.brandName }));
    //   }
    // },
    // async getChexSelect(seriesId, params) {
    //   let res = await getChexSelect(seriesId, params);
    //   if (res.resultCode == 200) {
    //     this.topFilterList.find(x => x.fieldName === 'seriesId').itemList = res.data.map(x => ({ value: x.seriesId + '', text: x.seriesName }));
    //   }
    // },
    // async queryModelBySeriesId(seriessid) {
    //   let res = await queryModelBySeriesId({ seriessid: seriessid });
    //   if (res.resultCode == 200) {
    //     this.topFilterList.find(x => x.fieldName === 'modelId').itemList = res.data.map(x => ({ value: x.modelId + '', text: x.modelName }));
    //   }
    // },
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.topFilterList.find(x => x.fieldName === 'repairTypeCode').itemList = this.repairList;
      // this.columns.find(x => x.dataIndex === 'repairTypeCode').dictItems = this.repairList;
      // this.columns.find(x => x.dataIndex === 'repairTypeCode').filterItems = this.repairList;
    },
    isEdit(row) {
      // console.log(row.down_tag);
      if (row.dataSources == '10451002' && Cookies.get('dataType') === 10461001) {
        // 店端账号、并且对应主机厂数据时不可以编辑
        return true;
      } else {
        return false;
      }
    },
    addHandle() {
      this.action = { type: 'add', title: '工单明细', visible: true, data: null };
    },
    editHandle(row) {
      this.action = { type: 'edit', title: '工单明细', visible: true, data: { ...row } };
    },
    changeHandle(val) {
      // let ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue || '';
      // this.fetchParams = Object.assign({ ownerCode: ownerCode }, val);
      // 搜索和重置都走
      let params = { ...this.fetchParams, ...val };
      if (params.ownerShortName && params.ownerShortName.length) {
        params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
      } else {
        params.ownerCode = undefined;
      }
      this.fetchParams = params;
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeDealerDialog() {
      this.dealerAction.visible = false;
    },
    saveDealerDialog([params]) {
      this.dealerAction.visible = false;
      this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = params.dealerCode;
      this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = params.dealerShortname;
    },
    closeHandler(val, type) {
      this.action.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
